<template>
  <view class="register-container">
    <!-- 动态渐变背景 -->
    <view class="bg-gradient"></view>
    <!-- 装饰元素 -->
    <view class="decor decor-1"></view>
    <view class="decor decor-2"></view>
    
    <!-- 玻璃拟态注册卡片 -->
    <view class="register-card">
      <!-- 标题区域 -->
      <view class="register-header">
        <text class="register-title">创建账号</text>
        <text class="register-desc">填写以下信息，开启专属体验</text>
      </view>
      
      <!-- 注册表单 -->
      <view class="register-form">
        <!-- 用户名输入 -->
        <view class="form-group" :class="{ focused: usernameFocus }">
          <view class="input-box">
            <icon type="person" size="26" :color="usernameFocus ? '#FF6B6B' : '#999'"></icon>
            <input 
              type="text" 
              v-model="username"
              placeholder="设置用户名（2-12位）" 
              placeholder-style="color:#ccc"
              @focus="usernameFocus = true"
              @blur="usernameFocus = false"
              @input="validateUsername"
            />
          </view>
          <text class="error-tip" v-if="showUsernameError">{{ usernameError }}</text>
        </view>
        
        <!-- 密码输入 -->
        <view class="form-group" :class="{ focused: passwordFocus }">
          <view class="input-box">
            <icon type="lock" size="26" :color="passwordFocus ? '#FF6B6B' : '#999'"></icon>
            <input 
              type="password" 
              v-model="password"
              placeholder="设置密码（≥6位，含字母和数字）" 
              placeholder-style="color:#ccc"
              @focus="passwordFocus = true"
              @blur="passwordFocus = false"
              @input="validatePassword"
            />
          </view>
          <text class="error-tip" v-if="showPasswordError">{{ passwordError }}</text>
        </view>
        
        <!-- 确认密码输入 -->
        <view class="form-group" :class="{ focused: confirmFocus }">
          <view class="input-box">
            <icon type="lock" size="26" :color="confirmFocus ? '#FF6B6B' : '#999'"></icon>
            <input 
              type="password" 
              v-model="confirmPwd"
              placeholder="确认密码" 
              placeholder-style="color:#ccc"
              @focus="confirmFocus = true"
              @blur="confirmFocus = false"
              @input="validateConfirm"
            />
          </view>
          <text class="error-tip" v-if="showConfirmError">{{ confirmError }}</text>
        </view>
        
        <!-- 昵称输入 -->
        <view class="form-group" :class="{ focused: nickNameFocus }">
          <view class="input-box">
            <icon type="chatbubbles" size="26" :color="nickNameFocus ? '#FF6B6B' : '#999'"></icon>
            <input 
              type="text" 
              v-model="nickName"
              placeholder="设置昵称（2-8位）" 
              placeholder-style="color:#ccc"
              @focus="nickNameFocus = true"
              @blur="nickNameFocus = false"
              @input="validateNickName"
            />
          </view>
          <text class="error-tip" v-if="showNickNameError">{{ nickNameError }}</text>
        </view>
        
        <!-- 修复后的注册按钮（无语法错误） -->
        <button 
          class="register-btn"
          @click="handleRegister"
          :disabled="!isFormValid || registerLoading"
          :class="{ disabled: !isFormValid || registerLoading }"
        >
          <icon type="loading" size="20" color="#fff" v-if="registerLoading"></icon>
          <text v-if="registerLoading" style="margin-left: 10rpx;">注册中...</text>
          <text v-else>注册并登录</text>
        </button>
        
        <!-- 登录跳转 -->
        <view class="login-link">
          <text>已有账号？</text>
          <navigator url="/pages/login/login" class="login-text">
            立即登录
            <view class="underline"></view>
          </navigator>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      confirmPwd: '',
      nickName: '',
      usernameFocus: false,
      passwordFocus: false,
      confirmFocus: false,
      nickNameFocus: false,
      showUsernameError: false,
      showPasswordError: false,
      showConfirmError: false,
      showNickNameError: false,
      usernameError: '',
      passwordError: '',
      confirmError: '',
      nickNameError: '',
      registerLoading: false
    };
  },
  computed: {
    isFormValid() {
      return this.username.trim() !== '' && this.password.trim() !== '' && this.confirmPwd.trim() !== '' && this.nickName.trim() !== ''
        && !this.showUsernameError && !this.showPasswordError && !this.showConfirmError && !this.showNickNameError;
    }
  },
  methods: {
    validateUsername() {
      const username = this.username.trim();
      const reg = /^[a-zA-Z0-9_]{2,12}$/;
      if (username === '') {
        this.showUsernameError = true;
        this.usernameError = '用户名不能为空';
      } else if (username.length < 2 || username.length > 12) {
        this.showUsernameError = true;
        this.usernameError = '用户名长度为2-12位';
      } else if (!reg.test(username)) {
        this.showUsernameError = true;
        this.usernameError = '仅允许字母、数字、下划线';
      } else {
        this.showUsernameError = false;
      }
    },
    validatePassword() {
      const password = this.password.trim();
      if (password === '') {
        this.showPasswordError = true;
        this.passwordError = '密码不能为空';
      } else if (password.length < 6) {
        this.showPasswordError = true;
        this.passwordError = '密码长度不能少于6位';
      } else if (!/^(?=.*[a-zA-Z])(?=.*\d)/.test(password)) {
        this.showPasswordError = true;
        this.passwordError = '密码需包含字母和数字';
      } else {
        this.showPasswordError = false;
      }
    },
    validateConfirm() {
      const confirmPwd = this.confirmPwd.trim();
      if (confirmPwd === '') {
        this.showConfirmError = true;
        this.confirmError = '请确认密码';
      } else if (confirmPwd !== this.password.trim()) {
        this.showConfirmError = true;
        this.confirmError = '两次密码不一致';
      } else {
        this.showConfirmError = false;
      }
    },
    validateNickName() {
      const nickName = this.nickName.trim();
      if (nickName === '') {
        this.showNickNameError = true;
        this.nickNameError = '昵称不能为空';
      } else if (nickName.length < 2 || nickName.length > 8) {
        this.showNickNameError = true;
        this.nickNameError = '昵称长度为2-8位';
      } else {
        this.showNickNameError = false;
      }
    },
    async handleRegister() {
      this.validateUsername();
      this.validatePassword();
      this.validateConfirm();
      this.validateNickName();
      if (!this.isFormValid) return;

      this.registerLoading = true;

      try {
        const res = await uniCloud.callFunction({
          name: 'userRegister',
          data: {
            account: this.username.trim(),
            password: this.password.trim(),
            nickName: this.nickName.trim()
          }
        });

        // 关键：强制清理返回结果中的特殊字符（解决 JSON 解析失败问题）
        let resultStr = typeof res.result === "string" ? res.result : JSON.stringify(res.result);
        resultStr = resultStr.replace(/[^\x20-\x7E]/g, ""); // 只保留可打印ASCII字符，移除非法字符
        const result = JSON.parse(resultStr);

        // 后续结果处理
        if (result.code === 200) {
          uni.setStorageSync('isLogin', true);
          uni.setStorageSync('currentUser', {
            username: this.username.trim(),
            nickName: this.nickName.trim(),
            accountId: result.data?.accountId || '' // 可选链避免 undefined 报错
          });
          uni.showToast({ title: '注册成功', icon: 'success', duration: 1200 });
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/demos/cardViewPage/cardViewPage",
              success: () => {
                uni.setTabBarItem({
                  index: 3,
                  text: "我的",
                  iconPath: "/static/mine.png",
                  selectedIconPath: "/static/mine-selected.png"
                });
              }
            });
          }, 1200);
        } else if (result.code === 400) {
          this.shakeForm();
          uni.showToast({ title: result.msg || '用户名已被占用', icon: 'none', duration: 2000 });
        } else {
          uni.showToast({ title: result.msg || '注册失败', icon: 'none', duration: 2000 });
        }
      } catch (e) {
        uni.showToast({ title: '注册出错，请重试', icon: 'none', duration: 2000 });
        console.log('注册出错详情：', e.message); // 只打印错误信息，避免复杂对象
      } finally {
        this.registerLoading = false;
      }
    },
    shakeForm() {
      const formDom = document.querySelector('.register-form');
      if (formDom) {
        formDom.style.animation = 'shake 0.5s ease';
        setTimeout(() => {
          formDom.style.animation = '';
        }, 500);
      }
    }
  }
};
</script>

<style scoped>
@keyframes shake {
  0%, 100% { transform: translateX(0); }
  20% { transform: translateX(-10rpx); }
  40% { transform: translateX(10rpx); }
  60% { transform: translateX(-5rpx); }
  80% { transform: translateX(5rpx); }
}

.register-container {
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
}

.bg-gradient {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #FF6B6B 0%, #4ECDC4 100%);
  z-index: 0;
  animation: gradientShift 15s ease infinite;
  background-size: 200% 200%;
}

@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.decor {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  filter: blur(50rpx);
  animation: float 8s ease-in-out infinite;
}

.decor-1 {
  width: 450rpx;
  height: 450rpx;
  top: 15%;
  right: 15%;
  animation-delay: 0s;
}

.decor-2 {
  width: 550rpx;
  height: 550rpx;
  bottom: 10%;
  left: 10%;
  animation-delay: 3s;
}

@keyframes float {
  0% { transform: translateY(0) translateX(0); }
  50% { transform: translateY(-30rpx) translateX(-30rpx); }
  100% { transform: translateY(0) translateX(0); }
}

.register-card {
  width: 100%;
  max-width: 550rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10rpx);
  border-radius: 30rpx;
  padding: 80rpx 40rpx;
  box-shadow: 0 20rpx 60rpx rgba(255, 107, 107, 0.1);
  z-index: 1;
  position: relative;
}

.register-header {
  text-align: center;
  margin-bottom: 80rpx;
}

.register-title {
  font-size: 42rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
  display: block;
}

.register-desc {
  font-size: 24rpx;
  color: #666;
  opacity: 0.8;
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 35rpx;
}

.form-group {
  transition: all 0.3s ease;
}

.form-group.focused .input-box {
  border-color: #FF6B6B;
  box-shadow: 0 0 0 2rpx rgba(255, 107, 107, 0.2);
}

.input-box {
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  height: 96rpx;
  background: rgba(255, 255, 255, 0.8);
  border: 2rpx solid #eee;
  border-radius: 48rpx;
  transition: all 0.3s ease;
}

.input-box input {
  flex: 1;
  height: 100%;
  font-size: 30rpx;
  color: #333;
  margin: 0 20rpx;
}

.error-tip {
  font-size: 22rpx;
  color: #F53F3F;
  margin-left: 30rpx;
  margin-top: 8rpx;
  display: block;
}

.register-btn {
  height: 100rpx;
  line-height: 100rpx;
  font-size: 32rpx;
  color: #fff;
  background: linear-gradient(90deg, #FF6B6B 0%, #FF8E8E 100%);
  border-radius: 50rpx;
  box-shadow: 0 10rpx 30rpx rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
}

.register-btn:not(.disabled):active {
  transform: scale(0.98);
  box-shadow: 0 5rpx 15rpx rgba(255, 107, 107, 0.2);
}

.register-btn.disabled {
  background: #ccc;
  box-shadow: none;
}

.login-link {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10rpx;
  margin-top: 40rpx;
  font-size: 24rpx;
  color: #666;
}

.login-text {
  color: #FF6B6B;
  font-weight: 500;
  position: relative;
  padding-bottom: 5rpx;
}

.underline {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2rpx;
  background: #FF6B6B;
  transition: width 0.3s ease;
}

.login-text:active .underline {
  width: 100%;
}
</style>